<template>
  <div class="project-milestones">
    <div class="card-title">资料信息</div>
    <div class="material">
      <el-tabs v-model="milestoneSort" @tab-click="handleClick">
        <el-tab-pane :name="item.milestoneSort.toString()" :key="item.milestoneSort" v-for="(item, index) in projectMilestones">
          <span slot="label">
            <div class="tabRadius">{{ item.milestoneSort }}</div>
            <div>{{ item.milestoneName }}</div>
          </span>
          <el-button type="primary" size="small" class="add-materials" @click="handleAddMaterials(item.materialsFormVoList,index)">新增材料</el-button>
          <el-table :data="item.materialsFormVoList" class="material-table" style="width: 100%;">
            <el-table-column prop="sort" label="序号" width="60" />
            <el-table-column prop="materialsName" label="材料名称" width="120">
              <template slot-scope="scope">
                <el-input
                  v-halfCharCode
                  size="small"
                  v-model="scope.row.materialsName"
                  placeholder="请输入材料名称"
                  maxlength="50"
                  @blur="handleMaterialsName(scope.row.materialsName,index,scope.$index)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="fileBusId" label="文件名称" width="160">
              <template slot-scope="scope">
                <el-row :gutter="10">
                  <el-col :xs="6" :sm="7" :md="7" :lg="7" :xl="7">
                    <div class="grid-content bg-purple" style="line-height: 40px">
                      <el-upload
                        v-if="isUpload[scope.$index]"
                        class="upload-demo"
                        action="/admin/sys-file/upLodeFileAdd"
                        :auto-upload="true"
                        :data="httpRequestData"
                        :before-remove="beforeRemove"
                        :show-file-list="false"
                        :http-request="(params)=>{verifyUpload(params, scope)}"
                        :file-list="httpRequestFileLis"
                      >
                        <el-button size="small" icon="el-icon-upload">上传文件</el-button>
                      </el-upload>
                      <el-button v-else disabled size="small" icon="el-icon-upload">上传文件</el-button>
                    </div>
                  </el-col>
                  <el-col :xs="17" :sm="17" :md="17" :lg="17" :xl="17">
                    <div class="grid-content bg-purple-light" style="line-height: 40px">
                      <span>
                        {{scope.row.original}}
                        <i
                          v-if="scope.row.original"
                          class="el-icon-close"
                          style="margin-left: 5px;cursor: pointer;font-weight: bold"
                          @click="triggerBeforeRemove(scope)"
                        />
                        <i
                          v-if="scope.row.original"
                          class="el-icon-search"
                          style="margin-left: 10px;cursor: pointer;font-weight: bold"
                          @click="triggerBeforeDownload(scope)"
                        />
                      </span>
                    </div>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" width="120">
              <template slot-scope="scope">
                <el-input v-halfCharCode size="small" v-model="scope.row.remarks" placeholder="请输入内容" maxlength="200" @blur="handleProps" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click.native.prevent="handleMaterialsDelete(index,scope.$index, item.materialsFormVoList)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 图片、文档预览弹窗 -->
    <el-dialog :visible.sync="dialogVisibleView" append-to-body :close-on-click-modal="false">
      <img width="100%" :src="previewUrl" alt v-if="previewType === 'image'" />
      <vPdf :fileId="previewUrl" v-else-if="previewType === 'pdf'" />
    </el-dialog>
  </div>
</template>

<script>
import { delFiles, checkFiles } from "@/api/operate-construction-contract";
import vPdf from "@/components/v-pdf";
import { download } from "@/admin/api/common";
import { downloadBlob } from "@/utils";
import { initMilestones } from "../api/planning";
import { mapState } from 'vuex'
export default {
  name: "project-milestones",
  components: { vPdf },
  props: {
    projectId: {
      type: String,
      default: ''
    },
    milestonesList: {
      type: Array,
      default: []
    }
  },
  data () {
    return {
      //里程碑默认页数
      milestoneSort: "1",
      //文件上传
      httpRequestData: {},
      busId: "",
      modelType: "milestone",
      httpRequestFileLis: [],
      url: "/admin/sys-file/upLodeFileAdd",
      //预览
      dialogVisibleView: false,
      // 预览文件的地址
      previewUrl: "",
      // 预览弹窗展示的类型
      previewType: "",
      //文件是否上传
      isUpload: [],
      // 里程碑详细内容
      projectMilestones: [],
      //是否可以保存
      isMaterialsName: false,
    }
  },
  computed: {
    ...mapState(['canUploadFile'])
  },
  methods: {
    // 上传文件前校验
    handleUpload (file) {
      console.log(file)
    },
    //上报切换事件
    handleClick (tab) {

      this.isUpload = [];
      this.selected = tab.index;
      // 如果文件busid为空那么就可以上传
      if (this.projectMilestones[tab.index]) {
        this.projectMilestones[tab.index].materialsFormVoList.map(
          (item, index) => {
            if (
              item.fileBusId === null ||
              item.fileBusId === "" ||
              item.fileBusId === undefined
            ) {
              this.isUpload.push(true);
            } else {
              this.isUpload.push(false);
            }
          }
        );
      } else {
        this.isUpload.push(true);
      }
    },
    //移除文件
    triggerBeforeRemove (item) {
      this.beforeRemove(item);
    },
    beforeRemove (file) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delFiles(file.row.fileBusId, this.modelType).then(resp => {
            if (resp.data.code === 0) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              file.row.original = "";
              file.row.fileBusId = "";
              this.isUpload[file.$index] = true;
            } else {
              this.$message({
                type: "error",
                message: "删除失败!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    verifyUpload (params, row) {
      if (params.file.size > 1 * 1024 * 1024) {
        this.$confirm('您上传的超过500M，文件较大，预期消耗时间较多，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.httpRequest(params, row)
        }).catch(() => {
          this.$message('已取消上传')
        })
      } else {
        this.httpRequest(params, row)
      }
    },
    // 文件上传
    httpRequest (params, row) {
      try {
        if (params.file.size > 100 * 1024 * 1024 * 1024) {
          this.$message({
            type: "error",
            message: `上传文件大小不能超过100GB!`
          });
          return;
        }
        let formatType = params.file.name.split(".")[1];
        if (this.canUploadFile.indexOf(formatType) === -1) {
          this.$message.error(
            `文件上传不支持该格式文件，目前仅支持${this.canUploadFile.join(',')}格式文件！`
          );
          return;
        }
        // 用FormData存放上传文件
        let formData = new FormData();
        formData.append("file", params.file);
        formData.append("module", this.modelType);
        formData.append("busId", this.busId);
        this.http.post(this.url, formData).then(resp => {
          if (resp.data.code === 0) {
            row.row.original = params.file.name;
            row.row.fileBusId = resp.data.data;
            this.isUpload[row.$index] = false;
            this.projectMilestones.map(it => it.projectId = this.projectId)
            this.$emit('fileBusId', this.projectMilestones)
          } else {
            this.$message.error("文件上传失败！");
          }
        });
      } catch (e) {
        console.log(e);
      }
    },
    // PDF预览\文件下载
    triggerBeforeDownload (item) {
      if (item.row.fileId === null) {
        this.$message.warning("文件暂未上传到服务器，无法下载！");
      } else {
        if (item.row.original.split(".")[1] === "pdf") {
          checkFiles(item.row.fileId).then(res => {
            if (res.data.code === 0) {
              this.previewType = "pdf";
              this.previewUrl = item.row.fileId;
              this.dialogVisibleView = true;
            } else {
              this.$message.warning("文件不存在或已删除！");
            }
          });
        } else if (
          item.row.original.split(".")[1] === "jpg" ||
          item.row.original.split(".")[1] === "png" ||
          item.row.original.split(".")[1] === "jpeg"
        ) {
          checkFiles(item.row.fileId).then(res => {
            if (res.data.code === 0) {
              this.previewType = "image";
              this.previewUrl = "/admin/sys-file/img/" + item.row.fileId;
              this.dialogVisibleView = true;
            } else {
              this.$message.warning("文件不存在或已删除！");
            }
          });
        } else {
          checkFiles(item.row.fileId).then(res => {
            if (res.data.code === 0) {
              download(
                "/admin/sys-file/download/" + item.row.fileId,
                this.modelType
              ).then(response => {
                downloadBlob(response.data, item.row.original);
              });
            } else {
              this.$message.warning("文件不存在或已删除！");
            }
          });
        }
      }
    },
    // hxf-0910-是否为默认项目，默认选择否
    handleClickToUpdateItem (obj) {
      initMilestones(obj).then(res => {
        if (res.data.code === 0) {
          this.projectMilestones = res.data.data;
          // 新增回显初始化加载自动点击tabs第一个
          this.handleClick({ index: 0 });
          this.$forceUpdate();
        } else {
          this.$message.error("未获取到里程碑信息！");
        }
      });
    },
    //修改材料名称或者备注时，抛出去
    handleMaterialsName (val, mIndex, index) {
      //找出当前下标的标志信息，将当前的标志信息从中删除
      let sort = this.projectMilestones[mIndex].materialsFormVoList[index].sort
      if (val === '') {
        this.getIsMaterialsName()
        this.$emit('isMaterialsName', this.isMaterialsName)
      } else {
        this.getIsMaterialsName()
        this.$emit('isMaterialsName', this.isMaterialsName)
        this.handleProps()
      }
    },
    handleProps () {
      this.$emit('fileBusId', this.projectMilestones)
    },
    //新增材料
    handleAddMaterials (data, index) {
      this.projectMilestones[index].materialsFormVoList.push({
        fileBusId: '',
        fileId: '',
        fileSize: '',
        fileUploadTime: '',
        materialsId: '',
        materialsName: '',
        original: '',
        recordId: '',
        remarks: '',
        sort: data.length + 1
      })
      this.isUpload[data.length - 1] = true
      this.$emit('fileBusId', this.projectMilestones)
      this.$nextTick(() => {
        this.getIsMaterialsName()
      })
    },
    //jiaj 验证是否全部填写材料名称
    getIsMaterialsName () {
      const res = this.projectMilestones.every(item => {
        return item.materialsFormVoList.every(i => i.materialsName)
      })
      this.isMaterialsName = res
      this.$emit('isMaterialsName', res)
    },
    //删除材料
    handleMaterialsDelete (mIndex, index, rows) {
      let dSort = rows[index].sort
      rows.splice(index, 1);
      rows.map((it, inx) => it.sort = inx + 1)
      this.isUpload.splice(index, 1)
      this.$emit('fileBusId', this.projectMilestones)
      this.$nextTick(() => {
        this.getIsMaterialsName()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.project-milestones {
  .material {
    padding-top: 16px;
    overflow: hidden;
    .add-materials {
      float: right;
      margin: 16px 0 20px 0;
    }
    .material-table {
      margin: 20px 0;
      position: relative;
    }
  }
}
</style>
